package com.hr.leetcode.树和二叉树和二叉搜索树;

/**
 * @author 周恒哲
 * @date 2020/05/17
 **/
public class _236_二叉树的最近公共祖先 {
    //利用当前的节点是否等于根节点来判断
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (p.val == root.val || q.val == root.val) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        /*if (left==null){
            return right;
        }
        if (right==null){
            return left;
        }
        if (left==null&&right==null){
            return root;
        }
        return root;*/
        //上面注释的可以用下面这一句概括
        return left == null ? right : right == null ? left : root;
    }
}
